﻿Imports System.Windows.Threading
Imports System.Threading.Tasks
Imports System.Net
Imports HtmlAgilityPack
Imports System.Collections.ObjectModel
Imports FuncClasses

Public Class Hermes
    Implements IPackager

    Private _id, _token As String
    WithEvents timer As DispatcherTimer
    WithEvents myWebClient, myWebClient2, tokenclient As New System.Net.WebClient
    WithEvents UIControl As New HermesControl

    Public Sub New(ByVal ID As String)
        _id = ID
        RequestNewToken()
        If String.IsNullOrEmpty(ID) = False Then
            Try : RefreshState() : Catch ex As Exception : End Try
        End If
    End Sub

    Public Property Package_ID As String Implements IPackager.Package_ID
        Get
            Return _id
        End Get
        Set(value As String)
            _id = value
            Try : RefreshState() : Catch ex As Exception : End Try
        End Set
    End Property

    Public Sub RefreshState() Implements IPackager.RefreshState
        GetAllStates()
    End Sub

    Public ReadOnly Property InfoControl As System.Windows.UIElement Implements IPackager.InfoControl
        Get
            Return UIControl
        End Get
    End Property

    Private Sub RequestedRefresh() Handles UIControl.RefreshRequested
        RefreshState()
    End Sub

#Region "Token"
    Private Sub RequestNewToken()
        Dim t As Task = Task.Factory.StartNew(Sub()
                                                  Dim s As String = tokenclient.DownloadString(New Uri("https://www.myhermes.de/wps/portal/paket/Home/privatkunden/sendungsverfolgung/"))
                                                  Dim doc As New HtmlDocument
                                                  doc.LoadHtml(s)
                                                  For Each item As HtmlNode In doc.DocumentNode.SelectNodes("//form[@id=""shipmentTracingDTO""]")
                                                      If item.Attributes("id").Value = "shipmentTracingDTO" Then
                                                          Dim token As String = item.Attributes("action").Value.ToString
                                                          _token = token
                                                          Exit For
                                                      End If

                                                  Next
                                              End Sub)
    End Sub

    Private Property Token As String
        Get
            Return _token
        End Get
        Set(value As String)
            _token = value
        End Set
    End Property
#End Region

#Region "Letzter Status"
    WithEvents dclient As New Net.WebClient()
    WithEvents timer1 As New DispatcherTimer
    Dim infolaststate As KeyValuePairs

    Public Sub GetLastState() Implements IPackager.GetLastState
        infolaststate = Nothing
        dclient2.Encoding = Text.Encoding.UTF8
        Do While String.IsNullOrEmpty(Token)
            Threading.Thread.Sleep(100)
        Loop
        dclient.DownloadStringAsync(New Uri("https://www.myhermes.de/" + Token + "?shipmentID=" + Package_ID))
        timer1.Interval = New TimeSpan(0, 0, 0, 0, 5)
        timer1.Start()
    End Sub

    Private Sub CompletedLastState(sender As Object, e As DownloadStringCompletedEventArgs) Handles dclient.DownloadStringCompleted
        Try
            '### Analyse des Results ###'
            Dim doc As New HtmlDocument
            doc.LoadHtml(e.Result)
            Dim link As HtmlNode
            link = doc.DocumentNode.SelectSingleNode("/html/body/div/div/table/tr/td/div/div[1]/div/div/table/tbody/tr/td[4]") 'Datum
            Dim datum As String = link.InnerText.Trim

            link = doc.DocumentNode.SelectSingleNode("/html/body/div/div/table/tr/td/div/div[1]/div/div/table/tbody/tr/td[5]") 'Letzte Meldung
            Dim letzterstatus As String = link.InnerText.Trim

            link = doc.DocumentNode.SelectSingleNode("/html/body/div/div/table/tr/td/div/div[1]/div/div/table/tbody/tr/td[1]") 'Empfänger
            Dim temp() As String = link.InnerText.Trim.Replace(vbCrLf, "").Split(vbTab)
            Dim empfänger As String = ""
            For Each s As String In temp
                If String.IsNullOrEmpty(s) = False Then
                    empfänger += s + " "
                End If
            Next

            infolaststate = New KeyValuePairs(datum, letzterstatus, empfänger)
        Catch ex As Exception : End Try
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles timer1.Tick
        If infolaststate IsNot Nothing Then
            UIControl.SetLastState(infolaststate)
            timer1.Stop()
        End If
    End Sub

#End Region

#Region "Details and LastState"
    WithEvents dclient2 As New Net.WebClient()
    WithEvents timer2 As New DispatcherTimer
    Dim details As New ObservableCollection(Of KeyValuePairs)

    Public Sub GetAllStates() Implements IPackager.GetAllStates
        details.Clear()
        infolaststate = Nothing
        Do While String.IsNullOrEmpty(Token)
            Threading.Thread.Sleep(100)
        Loop
        Dim s As String = "https://www.myhermes.de" + Token + "?shipmentID=" + Package_ID
        dclient2.Encoding = Text.Encoding.UTF8
        dclient2.DownloadStringAsync(New Uri(s))
        timer2.Interval = New TimeSpan(0, 0, 0, 0, 5)
        timer2.Start()
    End Sub

    Private Sub CompletedDetails(sender As Object, e As DownloadStringCompletedEventArgs) Handles dclient2.DownloadStringCompleted
        Try
            '### Analyse des Results ###'
            Dim doc As New HtmlDocument
            doc.LoadHtml(e.Result)
            Dim link As HtmlNode
            'Details'
            link = doc.DocumentNode.SelectSingleNode("//table[@class=""content_table table_shipmentDetails""]/tbody")
            For Each item As HtmlNode In link.ChildNodes
                If item.Name = "tr" Then
                    Dim itemslist As New Collection(Of String)
                    For Each subitem As HtmlNode In item.ChildNodes
                        If subitem.Name = "td" Then
                            itemslist.Add(subitem.InnerText.Trim)
                        End If
                    Next
                    '### Datum - Uhrzeit - Text ###'
                    details.Add(New KeyValuePairs(itemslist(0), itemslist(1), itemslist(2)))
                End If
            Next

            'LastState'
            'content_table table_shipmentOverview
            link = doc.DocumentNode.SelectSingleNode("//table[@class=""content_table table_shipmentOverview""]/tbody/tr/td[4]") 'Datum
            Dim datum As String = link.InnerText.Trim

            link = doc.DocumentNode.SelectSingleNode("//table[@class=""content_table table_shipmentOverview""]/tbody/tr/td[5]") 'Letzte Meldung
            Dim letzterstatus As String = link.InnerText.Trim

            link = doc.DocumentNode.SelectSingleNode("//table[@class=""content_table table_shipmentOverview""]/tbody/tr/td[1]") 'Empfänger
            Dim temp() As String = link.InnerText.Trim.Replace(vbCrLf, "").Split(vbTab)
            Dim empfänger As String = ""
            For Each s As String In temp
                If String.IsNullOrEmpty(s) = False Then
                    empfänger += s + " "
                End If
            Next

            infolaststate = New KeyValuePairs(datum, letzterstatus, empfänger)
        Catch ex As Exception : End Try
    End Sub

    Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles timer2.Tick
        If infolaststate IsNot Nothing Then
            timer2.Stop()
            UIControl.SetLastState(infolaststate)
            UIControl.SetDetails(details)
        End If
    End Sub
#End Region

    Public ReadOnly Property Details1 As ObservableCollection(Of FuncClasses.KeyValuePairs) Implements IPackager.Details
        Get
            Return details
        End Get
    End Property

    Public ReadOnly Property LastState As String Implements IPackager.LastState
        Get
            Return infolaststate.Value
        End Get
    End Property

    Public ReadOnly Property Packager As Packager Implements IPackager.Packager
        Get
            Return PacketTracking.Packager.Hermes
        End Get
    End Property
End Class
